using System;
using System.Globalization;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Data.Converters;
using Avalonia.Media;
using Avalonia.Threading;
using mas.ViewModels;
using ScottPlot;

namespace mas.Views;

public partial class PlotWndow : Window
{
    // 定时器，用于定时更新图表，50ms
    readonly DispatcherTimer _updatePlotTimer = new() { Interval = TimeSpan.FromMilliseconds(50) };
    
    // 定义转换器
    public static readonly BoolToTextConverter BoolToTextConverter = new();
    public static readonly ChannelColorConverter ChannelColorConverter = new();
    public static readonly ChannelVisibilityConverter ChannelVisibilityConverter = new();
    
    public PlotWndow()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;  
        _updatePlotTimer.Tick += OnUpdatePlotTimerTick;
        _updatePlotTimer.Start();
        InitializePlotStyle();
    }
    
    // 初始化图表样式
    private void InitializePlotStyle()
    {
        MainPlot.Plot.FigureBackground.Color = ScottPlot.Colors.Gray;
        MainPlot.Plot.DataBackground.Color = ScottPlot.Colors.Gray;      
        MainPlot.Plot.Grid.MajorLineColor = ScottPlot.Colors.White;  
    }
    
    // 定时器触发的图表更新事件
    private void OnUpdatePlotTimerTick(object? sender, EventArgs e)
    {
        if (DataContext is PlotWindowViewModel viewModel && !viewModel.IsPaused)
        {
            bool hasNewData = false;
            foreach (var channel in viewModel.PlotChannels)
            {
                if (channel.Logger.HasNewData)
                {
                    hasNewData = true;
                    break;
                }
            }
            
            if (hasNewData)
            {
                // 配置X轴时间格式化
                MainPlot.Plot.Axes.Bottom.TickGenerator = new ScottPlot.TickGenerators.NumericAutomatic
                {
                    LabelFormatter = ms => 
                    {
                        TimeSpan ts = TimeSpan.FromMilliseconds(ms);
                        return $"{ts.Minutes:D2}:{ts.Seconds:D2}.{ts.Milliseconds:D3}";
                    },
                };
                
                // Y轴自动适配数值范围
                MainPlot.Plot.Axes.AutoScaleY();
                MainPlot.Refresh();
            }
        }
    }
    
    // 数据上下文变更时初始化图表
    private void OnDataContextChanged(object? sender, EventArgs e)
    {
        if (DataContext is PlotWindowViewModel viewModel)
        {
            MainPlot.Plot.PlottableList.Clear();
            
            // 定义不同通道的颜色
            var colors = new ScottPlot.Color[] {
                ScottPlot.Colors.Blue,
                ScottPlot.Colors.Green,
                ScottPlot.Colors.Orange,
                ScottPlot.Colors.Red,
                ScottPlot.Colors.Purple
            };
            
            // 为每个通道添加一个DataLogger
            for (int i = 0; i < viewModel.PlotChannels.Count; i++)
            {
                var channel = viewModel.PlotChannels[i];
                MainPlot.Plot.PlottableList.Add(channel.Logger);
                
                // 为每个通道设置不同颜色
                channel.Logger.Color = colors[i % colors.Length];
                channel.Logger.LineWidth = 2;
            }
            
            // 初始显示全部数据
            foreach (var channel in viewModel.PlotChannels)
            {
                channel.Logger.ViewSlide();
            }
        }
    }
    
    // 窗口关闭时停止定时器释放资源
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        _updatePlotTimer.Stop();
        _updatePlotTimer.Tick -= OnUpdatePlotTimerTick;
    }
}

// 布尔值到文本的转换器
public class BoolToTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool boolValue)
        {
            return boolValue ? "恢复更新" : "暂停更新";
        }
        return "暂停更新";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

// 通道颜色转换器
public class ChannelColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int channelNumber)
        {
            var colors = new Avalonia.Media.Color[] {
                Avalonia.Media.Colors.Blue,
                Avalonia.Media.Colors.Green,
                Avalonia.Media.Colors.Orange,
                Avalonia.Media.Colors.Red,
                Avalonia.Media.Colors.Purple
            };
            
            var color = colors[(channelNumber - 1) % colors.Length];
            return new SolidColorBrush(color);
        }
        return new SolidColorBrush(Avalonia.Media.Colors.White);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

// 通道可见性转换器
public class ChannelVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int channelNumber && parameter is string range)
        {
            var parts = range.Split('-');
            if (parts.Length == 2 && 
                int.TryParse(parts[0], out int start) && 
                int.TryParse(parts[1], out int end))
            {
                return channelNumber >= start && channelNumber <= end;
            }
            else if (parts.Length == 1 && int.TryParse(parts[0], out int single))
            {
                return channelNumber == single;
            }
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
